package com.chengliang.bbs.config;

import com.chengliang.bbs.filter.ValidateCodeFilter;
import com.chengliang.bbs.handler.FailureHandler;
import com.chengliang.bbs.handler.SuccessHandler;
import com.chengliang.bbs.point.MyLoginUrlAuthenticationEntryPoint;
import com.chengliang.bbs.service.impl.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author chengliang
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 登录地址名称
     */
    @Value("${security.login-url}")
    private String loginPath = "/user/login";

    /**
     * 验证码过滤器
     */
    private final ValidateCodeFilter validateCodeFilter;

    /**
     * 账号登陆验证
     */
    private final MyUserDetailsService userDetailsService;

    /**
     * 登陆验证失败处理器
     */
    private final FailureHandler failureHandler;

    /**
     * 登陆验证成功处理器
     */
    private final SuccessHandler successHandler;

    /**
     * 未登录处理器
     */
    private final MyLoginUrlAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    public WebSecurityConfig(MyUserDetailsService userDetailsService, ValidateCodeFilter validateCodeFilter, FailureHandler failureHandler, SuccessHandler successHandler, MyLoginUrlAuthenticationEntryPoint authenticationEntryPoint) {
        this.userDetailsService = userDetailsService;
        this.validateCodeFilter = validateCodeFilter;
        this.failureHandler = failureHandler;
        this.successHandler = successHandler;
        this.authenticationEntryPoint = authenticationEntryPoint;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //验证码的过滤器
        http
                // 自定义过滤器，配置到UsernamePasswordAuthenticationFilter之前
                .addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                //放行的请求
                .antMatchers("/sign/in","/collection/find","/q/**","/sign/top20List","/","/user/images/captcha.png","/user/forget/*","/user/reg","/user/login/qq/*").permitAll()
                .anyRequest().authenticated()
                .and()
                //表单登录
                .formLogin()
                //登录页面路径
                .loginPage("/user/login")
                //登录的请求地址
                .loginProcessingUrl(loginPath)
                //设置成功的响应处理器
                .successHandler(successHandler)
                //设置失败的响应处理器
                .failureHandler(failureHandler)
                .permitAll()
                .and()
                //登出
                .logout()
                .logoutUrl("/user/logout")
                .logoutSuccessUrl("/")
                .permitAll()
                .and()
                //自定义未登录响应处理器
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
                ;
        // 关闭CSRF跨域
        http.csrf().disable();
        //以下这句就可以控制单个用户只能创建一个session，也就只能在服务器登录一次
        http.sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry()).expiredUrl(loginPath);
    }

    /**
     * session注册器
     * @return
     */
    @Bean
    public SessionRegistry sessionRegistry(){
        return new SessionRegistryImpl();
    }

    /**
     * 自定义未登录响应处理器
     * @return
     */
    @Bean
    public AuthenticationEntryPoint myAuthenticationEntryPoint(){
        return new MyLoginUrlAuthenticationEntryPoint();
    }

    /**
     * 验证管理器
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 密码编码器
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * @param auth
     * @throws Exception
     * 密码比较
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //自定义验证业务 指定密码对比方式
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    /**
     * 放行静态资源
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
        web.ignoring().antMatchers("/res/**","/images/**");
    }


}
